package com.quartet.modules.user.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quartet.api.ApiResult;
import com.quartet.api.MapServerException;
import com.quartet.api.PageResult;
import com.quartet.api.ResultErrorEnum;
import com.quartet.modules.customer.entity.TCustomerInfo;
import com.quartet.modules.customer.service.TCustomerInfoService;
import com.quartet.modules.system.service.RoleService;
import com.quartet.modules.system.service.dto.RoleDto;
import com.quartet.modules.user.dto.TUserInfoAddRequestDto;
import com.quartet.modules.user.dto.TUserInfoQueryRequestDto;
import com.quartet.modules.user.dto.TUserInfoResponseDto;
import com.quartet.modules.user.entity.TUserInfo;
import com.quartet.modules.user.service.TUserInfoService;
import com.quartet.utils.RandomUtils;
import com.quartet.utils.constant.MapServerConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *
 * 用户信息表(TUserInfo)表控制层
 *
 * @author makejava
 * @since 2021-05-04 17:08:15
 */
@RestController
@RequestMapping("tUserInfo")
@Slf4j
@Api(tags = "业务：用户管理")
public class TUserInfoController  {
    /**
     * 服务对象
     */
    @Resource
    private TUserInfoService tUserInfoService;

    @Resource
    private TCustomerInfoService tCustomerInfoService;

    @Resource
    private RoleService roleService;

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * 分页查询所有数据
     *
     * @param tUserInfoRequestDto 查询实体
     * @return 所有数据
     */
    @ApiOperation("分页查询所有用户信息")
    @PostMapping("/query-page")
    public ApiResult<PageResult> selectUserPage(@RequestBody TUserInfoQueryRequestDto tUserInfoRequestDto) {
        log.info("---------selectUserPage begin, tUserInfoRequestDto is {}----------", tUserInfoRequestDto);
        IPage<TUserInfo> page = new Page<>(tUserInfoRequestDto.getCurrent(), tUserInfoRequestDto.getLimit());
        QueryWrapper<TUserInfo> queryWrapper = new QueryWrapper<>();

        if (!CollectionUtils.isEmpty(tUserInfoRequestDto.getCustomersCodeList())) {
            queryWrapper.lambda().in(TUserInfo::getCustomerCode, tUserInfoRequestDto.getCustomersCodeList());
        }

        if (StringUtils.isNotBlank(tUserInfoRequestDto.getUsername())) {
            queryWrapper.lambda().like(TUserInfo::getUsername, tUserInfoRequestDto.getUsername());
        }
        if (!ObjectUtils.isEmpty(tUserInfoRequestDto.getUserStatus())) {
            queryWrapper.lambda().eq(TUserInfo::getUserStatus, tUserInfoRequestDto.getUserStatus());
        }
        if (StringUtils.isNotBlank(tUserInfoRequestDto.getPhone())) {
            queryWrapper.lambda().like(TUserInfo::getPhone, tUserInfoRequestDto.getPhone());
        }
        if (!ObjectUtils.isEmpty(tUserInfoRequestDto.getCreateStartTime())) {
            queryWrapper.lambda().ge(TUserInfo::getCreateTime, tUserInfoRequestDto.getCreateStartTime());
        }
        if (!ObjectUtils.isEmpty(tUserInfoRequestDto.getCreateEndTime())) {
            queryWrapper.lambda().le(TUserInfo::getCreateTime, tUserInfoRequestDto.getCreateEndTime());
        }

        if (!ObjectUtils.isEmpty(tUserInfoRequestDto.getExpireStartTime())) {
            queryWrapper.lambda().ge(TUserInfo::getExpireTime, tUserInfoRequestDto.getExpireStartTime());
        }
        if (!ObjectUtils.isEmpty(tUserInfoRequestDto.getExpireEndTime())) {
            queryWrapper.lambda().le(TUserInfo::getExpireTime, tUserInfoRequestDto.getExpireEndTime());
        }
        if (StringUtils.isNotBlank(tUserInfoRequestDto.getField())) {
            queryWrapper.orderBy(true, tUserInfoRequestDto.isAsc(), tUserInfoRequestDto.getField());
        } else {
            queryWrapper.orderBy(true, tUserInfoRequestDto.isAsc(), MapServerConstant.CREATE_TIME);
        }
        IPage<TUserInfo> dbResult = tUserInfoService.page(page, queryWrapper);
        PageResult<TUserInfoResponseDto> pageResult = new PageResult();
        List<TUserInfoResponseDto> tCustomerInfoResponseDtoList = dbResult.getRecords().stream().map(tUserInfo -> {
            TUserInfoResponseDto tUserInfoResponseDto = BeanUtil.copyProperties(tUserInfo, TUserInfoResponseDto.class);
            if (StringUtils.isNotBlank(tUserInfo.getRoleId())) {
                RoleDto roleDto = roleService.findById(Long.parseLong(tUserInfo.getRoleId()));
                Optional.ofNullable(roleDto).ifPresent(r->tUserInfoResponseDto.setRoleName(r.getName()));
            }

            QueryWrapper<TCustomerInfo> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.lambda().eq(TCustomerInfo::getCustomerCode,tUserInfo.getCustomerCode());
            TCustomerInfo tCustomerInfo = tCustomerInfoService.getOne(queryWrapper1);
            if (!ObjectUtils.isEmpty(tCustomerInfo)){
                tUserInfoResponseDto.setCustomerName(tCustomerInfo.getCustomerName());
            }
            return tUserInfoResponseDto;
        }).collect(Collectors.toList());
        pageResult.setTotal(dbResult.getTotal());
        pageResult.setData(tCustomerInfoResponseDtoList);
        log.info("---------selectUserPage end, data is {}----------", pageResult);
        return ApiResult.ok(pageResult);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("通过主键查询单条用户信息")
    @GetMapping("/selectById")
    public ApiResult<TUserInfoResponseDto> selectById(@RequestParam("id") String id) {
        log.info("---------selectById begin, id is {}----------", id);
        TUserInfo tUserInfo = this.tUserInfoService.getById(id);
        if (!ObjectUtils.isEmpty(tUserInfo)) {
            TUserInfoResponseDto tUserInfoResponseDto = BeanUtil.copyProperties(tUserInfo, TUserInfoResponseDto.class);
            tUserInfoResponseDto.setRoleName(roleService.findById(Long.parseLong(tUserInfo.getRoleId())).getName());
            tUserInfoResponseDto.setPassword("");
            return ApiResult.ok(tUserInfoResponseDto);
        } else {
            return ApiResult.ok(null);
        }

    }

    /**
     * 新增数据
     *
     * @param tUserInfoAddRequestDto 实体对象
     * @return 新增结果
     */
    @ApiOperation("新增用户信息")
    @PostMapping("/add")
    public ApiResult add(@RequestBody TUserInfoAddRequestDto tUserInfoAddRequestDto) {
        log.info("---------addUser begin, tUserInfoRequestDto is {}----------", tUserInfoAddRequestDto);
        //校验是否有当前客户(非平台客户才校验)
        if ("1".equals(tUserInfoAddRequestDto.getIsApplyUser())){
            List<TCustomerInfo> tCustomerInfoList = tCustomerInfoService.list(new QueryWrapper<TCustomerInfo>().lambda().eq(TCustomerInfo::getCustomerCode, tUserInfoAddRequestDto.getCustomerCode()));
            if (CollectionUtils.isEmpty(tCustomerInfoList)) {
                throw new MapServerException(ResultErrorEnum.BMKPM001);
            }
        }
        if (!tUserInfoAddRequestDto.getPassword().equals(tUserInfoAddRequestDto.getPasswordConfirm())) {
            throw new MapServerException(ResultErrorEnum.BMKPT001);
        }
        TUserInfo tUserInfo = BeanUtil.copyProperties(tUserInfoAddRequestDto, TUserInfo.class);
        //密码加密
        tUserInfo.setPassword(encoder.encode(tUserInfo.getPassword()));
        tUserInfo.setUserId(RandomUtils.getUserId());
        return ApiResult.ok(this.tUserInfoService.save(tUserInfo));
    }

    /**
     * 修改数据
     *
     * @param tUserInfoAddRequestDto 实体对象
     * @return 修改结果
     */
    @ApiOperation("修改用户信息")
    @PutMapping("/update")
    public ApiResult update(@RequestBody TUserInfoAddRequestDto tUserInfoAddRequestDto) {
        log.info("---------updateUser begin, tUserInfoRequestDto is {}----------", tUserInfoAddRequestDto);
        TUserInfo tUserInfo = BeanUtil.copyProperties(tUserInfoAddRequestDto, TUserInfo.class);
        return ApiResult.ok(this.tUserInfoService.updateById(tUserInfo));
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @ApiOperation("删除用户信息")
    @PostMapping("/delete")
    public ApiResult delete(@RequestParam("id") String id) {
        log.info("---------deleteUser begin, id is {}----------", id);
        return ApiResult.ok(this.tUserInfoService.removeById(id));
    }

    /**
     * 重置密码
     *
     * @param id 实体对象
     * @return 修改结果
     */
    @ApiOperation("重置密码")
    @PutMapping("/resetPassword")
    public ApiResult resetPassword(@RequestParam("id") String id) {
        log.info("---------resetPassword begin, tUserInfoRequestDto is {}----------", id);
        UpdateWrapper<TUserInfo> updateWrapper = new UpdateWrapper();
        updateWrapper.lambda().eq(TUserInfo::getUserId, id).set(TUserInfo::getPassword, encoder.encode(MapServerConstant.RESET_PASSWORD));
        return ApiResult.ok(this.tUserInfoService.update(updateWrapper));
    }
}
